﻿using System;
using System.IO;
using System.Text;
/*
 * 代码已托管 https://gitee.com/dlgcy/dotnetcodes/tree/dlgcy/DotNet.Utilities/ConsoleHelper
 */
namespace DotNet.Utilities.ConsoleHelper
{
    /// <summary>
    /// [dlgcy] Console输出重定向
    /// 其他版本：DotNet.Utilities.WinformHelper.TextBoxWriter 和 DotNet.Utilities.LogHelper
    /// 用法示例：
    /// 在构造器里加上：Console.SetOut(new ConsoleWriter(s => { LogHelper.Write(s); }));
    /// </summary>
    /// <example>
    /// <code>
    /// public class Example
    /// {
    ///     public Example()
    ///     {
    ///         Console.SetOut(new ConsoleWriter(s => { LogHelper.Write(s); }));
    ///     }
    /// }
    /// </code>
    /// </example>
    public class ConsoleWriter : TextWriter
    {
        private readonly Action<string> _Write;
        private readonly Action<string> _WriteLine;

        public ConsoleWriter(Action<string> write, Action<string> writeLine)
        {
            _Write = write;
            _WriteLine = writeLine;
        }

        public ConsoleWriter(Action<string> write)
        {
            _Write = write;
            _WriteLine = write;
        }

        // 使用 UTF-16 避免不必要的编码转换
        public override Encoding Encoding => Encoding.Unicode;

        // 最低限度需要重写的方法
        public override void Write(string value)
        {
            _Write(value);
        }

        // 为提高效率直接处理一行的输出
        public override void WriteLine(string value)
        {
            _WriteLine(value);
        }
    }
}
